package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Page;
import com.nowcoder.community.utils.CommonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 多人协作开发时，常用的注解标注
 *
 * @todo: 待做
 * @fixme: 待修复
 * 快捷键定位：Alt+6
 *
 * 模板2：输出语句：
 * sout
 * 一些变型：
 * soutp:打印方法的形参
 * soutm:打印方法的名字
 * soutv:打印变量
 *
 * 模板3： 循环
 * 普通for循环：   fori（正向）
 * 增强for循环：  iter
 * （可以用于数组的遍历，集合的遍历）
 *
 * 模板4： 条件判断
 * ifn 或者  .null ：判断是否为null  （if null）
 * inn 或者 .nn ：判断不等于null   (if not null)
 *
 * 模板5： 属性修饰符：
 * psf  :public static final
 */
@Controller
public class AlphaController {
    @GetMapping(path = "/testModel")
    //fixme
    public void testModel(Model model) {
        model.addAttribute("name", "yang");
        Map<String, Object> map = new HashMap<>();
        map.put("name", "shu");
        map.put("age", 1);
        model.addAllAttributes(map);
        System.out.println(model.asMap());
    }

    @GetMapping(path = "/testModel2")
    public void testModel2(Model model) {
        model.addAttribute("name", "yang");
        Map<String, Object> map = new HashMap<>();
        map.put("name", "shu");
        map.put("age", 1);
        model.mergeAttributes(map);
        System.out.println(model.asMap());
    }

    @GetMapping(path = "/testModel3")
    public String testModel3(Model model) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "shu");
        map.put("age", 1);
        map.put("major", "计算机科学与技术");
        map.put("class", "计科一区");
        mapList.add(map);
        model.addAttribute("mapList", mapList);
        System.out.println(model.asMap());
        return "/testAlphaController";
    }

    //Cookies示例
    @GetMapping(path = "/cookies/set")
    @ResponseBody
    public String setCookies(HttpServletResponse response) {
        Cookie cookie = new Cookie("code", CommonUtil.generateUUID());
        cookie.setPath("/community/alpha");
        cookie.setMaxAge(60 * 10);
        response.addCookie(cookie);
        System.out.println(cookie.toString());
        return "return cookies";
    }

    @GetMapping(path = "/cookies/get")
    @ResponseBody
    public String getCookies(@CookieValue("code") String code) {
        System.out.println(code);
        return code;
    }

    /**
     * 分页模块测试：
     * 前端"/testMethod"请求传递过来的参数会被传入Page实体类接收，并把Page自动装配到ModelMap中，供前端调用
     */
    @GetMapping(path = "/testMethod")
    public String getIndexPage(Page page) {
        page.setRows(20);
        page.setPath("/testMethod");
        System.out.println(page.getCurrent());
        return "/testAlphaController";
    }

    /**
     * 对不确定参数个数时的一种表示<数组原理></>
     *
     * @param num
     */
    public void nums(int... num) {
       /* System.out.println(num[0]);
        System.out.println(num[1]);
        System.out.println(num[2]);*/
        System.out.println(num.length);
        System.out.println(num);
    }

    @PostMapping(path = "/ajax")
    @ResponseBody
    public String getJSONString(String name, Integer age) {
        Map<String, Object> map = new HashMap<>();
        map.put("yang", name);
        map.put("age", age);
        String jsonString = CommonUtil.getJSONString(200, "操作成功！", map);
        return jsonString;
    }

    @PostMapping(path = "/testMap")
    @ResponseBody
    public String getMapValue(@RequestBody Map<String, Object> map) {
        for (String key : map.keySet()) {
            System.out.println("key:" + key + ",value:" + map.get(key));
        }
        return CommonUtil.getJSONString(0, "请求成功", map);
    }

    /**
     * 测试response的字符输出流
     */
    @PostMapping(path = "/testWrite")
    public void testWrite(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(CommonUtil.getJSONString(1, "页面不见了！"));
    }

    /**
     * 手动控制springboot的错误页面处理机制
     */
    @GetMapping(path = "/testError")
    public String testError(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute("javax.servlet.error.status_code", 403);
        request.getRequestDispatcher("/error").forward(request, response);
        return null;
    }

    @GetMapping(path = "/testServletContext")
    public void testServletContext(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletContext servletContext = request.getServletContext();
        String encoding = servletContext.getResponseCharacterEncoding();
        String serverInfo = servletContext.getServerInfo();
        int sessionTimeout = servletContext.getSessionTimeout();
        //直接以html的形式输出
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("编码：" + encoding + ",服务器信息：" + serverInfo + ",session超时时间:" + sessionTimeout);
    }

}
